<?php
/**
 * Class PictureModule
 * 数据表 id url md5 path filename size mark
 */
class PictureModule extends Data{
    protected $table;

    protected static $selfObjectArray;
    protected function __construct($table) {
        parent::__construct();
        $this->table=!empty($table)&&validateVar($table)?$table:'likyh_photo';
    }

    /**
     * 初始化函数，并返回当前类
     * @param string $table 表名
     * @return PictureModule
     */
    public static function init($table = 'likyh_photo'){
        if(!isset(self::$selfObjectArray[$table])){
            self::$selfObjectArray[$table]=new PictureModule($table);
        }
        return self::$selfObjectArray[$table];
    }
    function install($comment = null){
        $comment=$this->db->quote($comment);
        $sql="CREATE TABLE IF NOT EXISTS `likyh_photo` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `url` VARCHAR(255) NULL,
              `md5` VARCHAR(255) NULL,
              `path` VARCHAR(255) NULL,
              `filename` VARCHAR(255) NULL,
              `size` DECIMAL(8,2) NULL,
              `mark` VARCHAR(255) NULL,
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT={$comment};";
        $this->db->sqlExec($sql);
        return true;
    }
    function add($url,$path=null,$filename=null,$size=null,$mark=null){
        $data['url']=$url;
        $data['md5']=md5_file($url);
        $data['path']=$path;
        $data['filename']=$filename;
        $data['size']=(double)$size;
        $data['mark']=$mark;
        if($this->db->insert($this->table,$data) == 1){
            return (int)$this->db->insertId();
        }
        return -1;
    }
    function delete($id){
        $id=(int)$id;
        return $this->db->delete($this->table,$id)==1;
    }

    /**
     * 搜出ids中第一张图
     * @param string $ids
     * @return array
     */
    function getFirst($ids){
        if(!empty($ids)){
            $id=explode(',',$ids,1);
            $sql="SELECT * FROM `{$this->table}` WHERE `id`=?";
            return $this->db->getOne($sql,$id);
        }
        return array();
    }

    /**
     * 搜出所有图片
     * @param string $ids
     * @return array
     */
    public function getDetail($ids){
        if(empty($ids)){
            return array();
        }
        $sql="select * from `{$this->table}` where FIND_IN_SET(id,?)";
        return $this->db->getAll($sql, $ids);
    }
    // 搜所有图片
    function getList($rows=30,$offset=0){
        $rows=(int)$rows;
        $offset=(int)$offset;
        $sql="SELECT * FROM `{$this->table}` WHERE 1 limit $offset,$rows";
        return $this->db->getList($sql);
    }
    // 检查图片是否已经存在 存在返回id
    function checkExist($md5,$size){
        $sql="SELECT `id` FROM `{$this->table}` WHERE `md5`=? and `size`=?";
        return $this->db->getValue($sql,$md5,$size);
    }
} 